<template>
  <section>
    <d2-container type="full" v-if="!show.edit && !show.view">
      <section class="data-list-box">
        <mk-search-form :model="query" v-if="permBtn.queryButton" @search="goPage(1)">
          <el-form-item class="inline-item" prop="dayDate">
            <el-date-picker v-model.trim="query.params.dayDate" @clear="goPage(1)" @keyup.native.enter="goPage(1)"
              type="date" size="mini" clearable format="yyyy-MM-dd" value-format="yyyy-MM-dd" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item class="inline-item" prop="nickName" v-if="permBtn.searchShop">
            <el-select v-model="query.params.shop" size="mini" @clear="goPage(1)" clearable placeholder="选择店铺">
              <el-option v-for="item in shopList" :key="item.shopName" :label="item.shopName" :value="item.shopName">
              </el-option>
            </el-select>
          </el-form-item>
        </mk-search-form>
        <div class="table-operate">
          <table-field-filter :fields="fields" @showChange="updataKey += 1" />
          <mk-table-button dis-delete :dis-add="!permBtn.createButton" @add="setPre">
            <el-button size="mini" icon="el-icon-upload" @click="exportEcx">导出</el-button>
          </mk-table-button>
        </div>
        <!-- 表格 -->
        <mk-el-table @sort="sortChange" :datas="datas" :key="updataKey" :height="tableHeight" :loadingText="loading.text"
          :loading="loading.list">
          <template v-for="field in fields" v-if="field.show">
            <el-table-column v-if="field.key == 'checkBox'" :align="field.align" type="selection" fixed="left"></el-table-column>
            <el-table-column v-else-if="field.key == 'toolButton'" :align="field.align" :label="field.name"
              :width="field.width" :fixed="field.fixed">
              <template slot-scope="scope">
                <mk-tool-button @view="goView(scope.row)" @edit="goEditOrAdd(scope.row)" :dis-delete="delPerm(scope.row)"
                  :dis-edit="!permBtn.updateButton" @delete="goDelete(scope.row)">
                </mk-tool-button>
              </template>
            </el-table-column>
            <el-table-column v-else show-overflow-tooltip :prop="field.key" :align="field.align" :label="field.name"
              :width="field.width" :sortable="field.enableSort ? 'custom' : false" :fixed="field.fixed"></el-table-column>
          </template>
        </mk-el-table>
        <mk-pagination :current-page="query.offset" :page-size="query.limit" :data-size="temp.dataSize" @go="goPage"
          @changePageSize="changePageSize" />
      </section>
    </d2-container>
    <!-- 选择日期和店铺 -->
    <el-dialog title="选择日期和店铺" :visible.sync="show.pre" width="30%">
      <el-form :model="preForm" :rules="rules" ref="preForm" label-width="100px">
        <el-form-item label="日期" prop="dayDate">
          <el-date-picker v-model.trim="preForm.dayDate" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="店铺" prop="shop">
          <el-select v-model="preForm.shop" placeholder="请选择店铺" :disabled="shopDis">
            <el-option v-for="item in shopList" :key="item.shopName" :label="item.shopName" :value="item.shopName">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="show.pre = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="clickAdd" size="mini">确 定</el-button>
      </span>
    </el-dialog>

    <!-- <el-dialog :title="dialogTitle" :visible.sync="addDialog" width="1200px" append-to-body >
      <GetReportInfo v-if="addDialog" :updateData="updateData" :pre="preForm" @close="close"/>
    </el-dialog> -->
  </section>
</template>

<script>

import Tools from '@/libs/utils.tool'
import { exportExecl } from '@/libs/util.export'
import { dirReportList, dirReportDelete, thisdaysend } from '@/api/modules/sys.report.api'
import { dirShopList } from '@/api/modules/sys.shop.api'
import GetReportInfo from './get-report-info'
import ViewReportInfo from './view-report-info'
import util from '@/libs/util'

export default {
  name: 'dir-report-info',
  components: {
    GetReportInfo
  },
  data() {
    return {
      dialogScale: false,
      addDialog: false,
      show: {
        edit: false,
        view: false,
        pre: false
      },
      preForm: {},
      rules: {
        dayDate: [{ required: true, message: '请选择日期', trigger: 'blur' }],
        shop: [{ required: true, message: '请选择店铺', trigger: 'blur' }]
      },
      updateData: {},
      updataKey: 0,
      heightL: 580,
      tableHeight: 580,
      // 查询条件
      query: {
        params: {},
        limit: 15, // 每页显示条数
        offset: 1, // 页码
        sort: {
          prop: 'dayDate',
          order: 'desc'
        }
      },
      permBtn: {
        createButton: false,
        queryButton: false,
        deleteButton: false,
        updateButton: false,
        resetButton: false,
        searchShop: false
      },
      // 返回数据列表
      datas: [],
      // 临时变量
      temp: {
        // 数据总调数
        dataSize: 0,
        // 当前选中的id
        id: '',
        //
        item: []
      },
      // 汇总数据
      totals: [],
      // 加载中效果
      loading: {
        // 获取列表数据中
        list: false,
        text: '加载中'
      },
      item_data: {},
      // 列表渲染数据列
      fields: [
        { key: 'dayDate', name: '记账日期', show: true, align: 'center', enableSort: true, fixed: false },
        { key: 'shop', name: '店铺', show: true, align: 'center', enableSort: false, fixed: false },
        { key: 'dayIncomeAllMoney', name: '当日收入合计', show: true, align: 'center', enableSort: true, fixed: false },
        { key: 'dayBalanceAllMoney', name: '当日余额合计', show: true, align: 'center', enableSort: true, fixed: false },
        { key: 'totalPayables', name: '应交款合计', show: true, align: 'center', enableSort: true, fixed: false },
        { key: 'difference', name: '差异', show: true, align: 'center', enableSort: true, fixed: false },
        { key: 'createdAt', name: '创建时间', show: true, align: 'center', enableSort: true, fixed: false },
        { key: 'toolButton', name: '操作', show: true, align: 'center', width: '280', enableSort: false, fixed: 'right' }
      ],
      // 店铺列表
      shopList: [],
      // 用户信息
      userInfo: JSON.parse(util.cookies.get('userInfo')),
      shopDis: false
    }
  },
  watch: {
    'heightL'(val) {
      this.updataKey += 1
      this.tableHeight = val
    }
  },
  mounted() {
    this.getShop()
    this.getWinHeight()
    this.getDataList()
    setTimeout(() => {
      this.getPerms()
    }, 700);
    if (this.userInfo.shopName) {
      this.query.params.shop = this.userInfo.shopName
      this.shopDis = true
    }
  },
  methods: {
    // 页面权限
    getPerms() {
      const perms = this.$store.state.d2admin.perms.permsArr
      if (perms.includes('*')) {
        this.permBtn.createButton = true
        this.permBtn.queryButton = true
        this.permBtn.searchShop = true
        this.permBtn.deleteButton = true
        this.permBtn.updateButton = true
        this.permBtn.resetButton = true
      } else {
        if (perms.includes('POST /api/private/daily/create')) {
          this.permBtn.createButton = true
        }
        if (perms.includes('POST /api/private/daily/list')) {
          this.permBtn.queryButton = true
        }
        if (perms.includes('POST /api/private/daily/update')) {
          this.permBtn.updateButton = true
          // this.permBtn.searchShop = true
        }

        if (perms.includes('StoreSearch')) {
          this.permBtn.searchShop = true
        }

        if (perms.includes('POST /api/private/daily/delete')) {
          this.permBtn.deleteButton = true
        }
        if (perms.includes('POST /api/private/daily/reset')) {
          this.permBtn.resetButton = true
        }
      }
    },
    // 获取所有商铺
    getShop() {
      dirShopList({ limit: 99, offset: 1, params: { shopName: '' } }).then(res => {
        this.shopList = res.data
      })
    },
    // 获取列表数据
    getDataList() {
      try {
        this.loading.list = true
        dirReportList(this.query).then(res => {
          const datas = res.data || []
          for (const data of datas) {
            // 时间格式化
            data.dayDate = data.dayDate && Tools.fmtLong2DateTime(data.dayDate, 'yyyy-MM-dd')
            data.createdAt = data.createdAt && Tools.fmtLong2DateTime(data.createdAt)
            data.updatedAt = data.updatedAt && Tools.fmtLong2DateTime(data.updatedAt)
          }
          this.datas = datas
          this.temp.dataSize = res.count
          this.loading.list = false
        })
      } catch (err) {
        this.$message.error('数据加载失败')
        this.loading.list = false
      }
    },
    // 删除数据
    goDelete(data) {
      this.$toast.confirm('此操作将永久删除该条数据, 是否继续?').then(() => {
        dirReportDelete({
          id: data.id,
          authorization: util.cookies.get('token')
        }).then(res => {
          this.$toast.success('删除成功')
          this.getDataList()
        }).catch(err => {
          console.log(err)
        })
      })
    },
    close() {
      this.show.edit = false
      this.show.view = false
      this.addDialog = false;
      this.getDataList()
    },
    // 跳到页
    goPage(pageNum) {
      this.query.offset = pageNum
      // 查询数据
      this.getDataList()
    },
    // 改变每页数据量
    changePageSize(size) {
      this.query.limit = size
      this.query.offset = 1
      this.getDataList()
    },
    // 重置查询条件
    resetQuery(formName) {
      this.$refs[formName].resetFields()
      this.goPage(1)
    },
    // 排序
    sortChange(row) {
      this.query.sort.order = row.order === 'ascending' ? 'asc' : 'desc'
      this.query.sort.prop = row.prop
      this.getDataList()
    },
    resetPwd(data) {
      this.show.reset = true
      this.resetPwdData.password = ''
      this.resetPwdData.id = data.id
    },
    // 添加前置
    setPre() {
      this.preForm = {}
      if (this.userInfo.shopName) {
        this.preForm.shop = this.userInfo.shopName
      }
      this.$set(this.preForm, 'dayDate', Tools.fmtLong2DateTime(Date.now(), 'yyyy-MM-dd'))
      this.show.pre = true
    },
    clickAdd() {
      this.$refs['preForm'].validate((valid) => {
        if (valid) {
          thisdaysend(this.preForm).then(res => {
            if (!res) {
              this.goEditOrAdd('add')
            } else {
              this.$toast.error(`${this.preForm.dayDate}日${this.preForm.shop}的日报已存在，请勿重复提交！`)
            }
          })
        }
      })
    },
    // 添加编辑
    goEditOrAdd(item) {
      this.show.pre = false
      // var dayDate = ''
      if (item !== 'add') {
        this.preForm = {
          dayDate: item.dayDate,
          shop: item.shop
        }
      } else {
        // dayDate = item.dayDate
        item = {}
      }
      // this.dialogTitle = item && item.id ? '编辑日报' : '新增日报';
      // this.updateData = item;
      // this.addDialog = true;
      this.$toast.showCustomModal(item && item.id ? '编辑' + item.dayDate + '日报' : '新增' + this.preForm.dayDate + '日报', GetReportInfo, { updateData: item, pre: this.preForm }, data => {
        if (data) {
          this.getDataList()
        }
      })
    },
    // 跳转到查看详情
    goView(data) {
      this.$toast.showCustomModal('查看' + data.dayDate + '日报', ViewReportInfo, { viewData: data || {} }, data => {
        // console.log(data)
      })
    },
    // 导出
    exportEcx() {
      exportExecl(this, this.fields, this.datas, '列表', new Date().toLocaleDateString() + '导出的列表')
    },
    // 获取窗口高度
    getWinHeight() {
      const that = this
      this.heightL = window.innerHeight - 320
      window.addEventListener('resize', () => {
        that.updataKey += 1
        that.heightL = window.innerHeight - 320
      })
    },
    // 删除权限判断
    delPerm(row) {
      let perms = JSON.parse(util.cookies.get('permMenus'))
      if (perms.includes('del:dailyReport:manager')) {
        var date = new Date(row.createdAt).getTime();
        var dataHour = 3600000 * 2 + date;
        if (new Date().getTime() > dataHour) {
          return true
        } else {
          return false
        }
      } else if (perms.includes('*') || perms.includes('POST /api/private/daily/delete')) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style scoped>
.scale {
  position: absolute;
  top: 20px;
  right: 50px;
}
</style>
